<template>
  <div class="tree-container">
    <el-input
      v-model="filterText"
      placeholder="输入关键字筛选"
      class="filter-input"
    ></el-input>
    <el-tree
      :data="treeData"
      :props="treeProps"
      :filter-node-method="filterNode"
      ref="tree"
      node-key="id"
      default-expand-all
      show-checkbox
      :check-strictly="true"
      @check-change="handleCheckChange"
      v-model="checkedKeys"
    ></el-tree>
    <div class="selected-info" v-if="checkedKeys.length > 0">
      <p>已选择节点ID: {{ checkedKeys.join(', ') }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      filterText: '',
      checkedKeys: [],
      // 添加操作顺序记录数组
      orderCheckList: [],
      treeProps: {
        children: 'children',
        label: 'name',
        disabled: 'disabled'
      },
      // 示例40个节点的列表数据
      nodeList: Array.from({length: 40}, (_, i) => {
        // 根节点
        if (i === 0) {
          return { id: -1, parentnodeid: null, name: `根节点` }
        }
        // 一级节点 (1-5)
        if (i >= 1 && i <= 5) {
          return { id: i, parentnodeid: -1, name: `节点${i}` }
        }
        // 二级节点 (6-20)
        if (i >= 6 && i <= 20) {
          const parentId = Math.floor((i - 6) / 3) + 1
          return { id: i, parentnodeid: parentId, name: `节点${parentId}-${i}` }
        }
        // 三级节点 (21-40)
        return { 
          id: i, 
          parentnodeid: Math.floor((i - 21) / 2) + 6, 
          name: `节点${Math.floor((i - 21) / 2) + 6}-${i}` 
        }
      }),
      treeData: []
    };
  },
  created() {
    // 转换列表为树形结构
    this.treeData = this.convertListToTree(this.nodeList)
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    // 列表转树形结构的方法
    convertListToTree(list) {
      const nodeMap = {};
      const tree = [];
      
      // 构建节点映射并添加children属性
      list.forEach(node => {
        nodeMap[node.id] = { ...node, children: [] };
      });
      
      // 构建树形结构
      list.forEach(node => {
        const currentNode = nodeMap[node.id];
        
        if (node.parentnodeid === null) {
          tree.push(currentNode);
        } else {
          const parentNode = nodeMap[node.parentnodeid];
          if (parentNode) {
            parentNode.children.push(currentNode);
          }
        }
      });
      
      // 添加isLeaf和disabled属性
      this.addAdditionalProperties(tree);
      
      return tree;
    },
    
    // 添加isLeaf和disabled属性
    addAdditionalProperties(nodes) {
      nodes.forEach(node => {
        node.isLeaf = node.children.length === 0;
        node.disabled = node.children.length !== 0;
        
        if (!node.isLeaf) {
          this.addAdditionalProperties(node.children);
        }
      });
    },
    
    // 筛选节点方法（父子不关联）
    filterNode(value, data) {
      if (!value) return true;
      return data.name.toLowerCase().includes(value.toLowerCase());
    },
    
    // 处理节点选择变化
    handleCheckChange(data, checked, indeterminate) {
      if (checked) {
        // 当checked为true时，添加数据到orderCheckList
        this.orderCheckList.push({
          timestamp: new Date().toISOString(),
          nodeId: data.id,
          nodeName: data.name,
          action: '选中'
        });
      } else {
        // 当checked为false时，删除orderCheckList中相同id的项
        this.orderCheckList = this.orderCheckList.filter(
          item => item.nodeId !== data.id
        );
      }
      
      // 当orderCheckList长度为3时，处理叶子节点禁用状态
      if (this.orderCheckList.length === 3) {
        // 获取已选中节点ID集合
        const selectedIds = new Set(this.orderCheckList.map(item => item.nodeId));
        
        // 递归遍历树形结构处理节点状态
        const traverseTree = (nodes) => {
          nodes.forEach(node => {
            // 仅处理叶子节点
            if (node.isLeaf) {
              // 不在选中列表中的叶子节点设置为禁用
              node.disabled = !selectedIds.has(node.id);
            } else {
              // 递归处理子节点
              traverseTree(node.children);
            }
          });
        };
        
        // 从根节点开始遍历
        traverseTree(this.treeData);
        
        // 手动更新checkedKeys以反映当前选中状态
        this.checkedKeys = Array.from(selectedIds);
      } 
      // 当orderCheckList长度小于3时，启用所有叶子节点
      else if (this.orderCheckList.length < 3) {
        // 递归遍历树形结构启用所有叶子节点
        const traverseTree = (nodes) => {
          nodes.forEach(node => {
            if (node.isLeaf) {
              node.disabled = false;
            } else {
              traverseTree(node.children);
            }
          });
        };
        
        traverseTree(this.treeData);
        
        // 手动更新checkedKeys以反映当前选中状态
        this.checkedKeys = this.orderCheckList.map(item => item.nodeId);
      }
      
      console.log('--orderCheckList--', this.orderCheckList);
      console.log('节点选择变化:', {
        id: data.id,
        name: data.name,
        checked,
        indeterminate,
        currentSelected: this.checkedKeys
      });
    }
  }
};
</script>

<style scoped>
.tree-container {
  width: 500px;
  margin: 20px;
}
.filter-input {
  margin-bottom: 16px;
  width: 100%;
}
.selected-info {
  margin-top: 16px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
    